package com.changgou.oauth.interceptor;

import com.alibaba.fastjson.JSON;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: HuxiWang
 * @Date: Create in 16:48 2021/1/21
 * @Description: token拦截器
 */
public class TokenRequestInterceptor implements RequestInterceptor {

    /*
            没有从数据库加载查询用户信息：
                1.没有令牌，生成令牌
                2.令牌携带过去到头文件中
                3.feign调用之前
                4.拦截器
         */
    // feign执行前拦截
    @Override
    public void apply(RequestTemplate template) {
//        String token = adminToken();
//        // 放入到头文件中
//        template.header("Authorization", "bearer " + token);

        // 获取用户的令牌，然后封装到头文件中

        // 记录了所有用户的数据
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 所有头名字
        Enumeration<String> headerNames = requestAttributes.getRequest().getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String nextElement = headerNames.nextElement();
            // 获取请求头
            String header = requestAttributes.getRequest().getHeader(nextElement);
            // 封装到下一个微服务
            template.header(nextElement, header);
        }
    }

    public String adminToken() {
        //证书文件路径
        String key_location = "changgou.jks";
        //秘钥库密码
        String key_password = "changgou";
        //秘钥密码
        String keypwd = "changgou";
        //秘钥别名
        String alias = "changgou";

        //访问证书路径 读取jks的文件
        ClassPathResource resource = new ClassPathResource(key_location);

        //创建秘钥工厂
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(resource, key_password.toCharArray());

        //读取秘钥对(公钥、私钥)
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair(alias, keypwd.toCharArray());

        //获取私钥
        RSAPrivateKey rsaPrivate = (RSAPrivateKey) keyPair.getPrivate();

        //自定义Payload
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("id", "1");
        tokenMap.put("name", "itheima");
        tokenMap.put("roles", "ROLE_VIP,ROLE_USER");

        //生成Jwt令牌
        Jwt jwt = JwtHelper.encode(JSON.toJSONString(tokenMap), new RsaSigner(rsaPrivate));

        //取出令牌
        String token = jwt.getEncoded();
//        System.out.println(encoded);

        return token;
    }

}












